package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.dao.SchoolDaoImpl;
import cn.edu.sdjzu.xg.eagle.entity.School;
import cn.edu.sdjzu.xg.eagle.exception.BaseException;
import cn.edu.sdjzu.xg.eagle.util.ControllerHelper;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import cn.edu.sdjzu.xg.eagle.util.Pagination;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

@WebServlet("/t2")
public class SchoolController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        JSONObject message_jsonObj = new JSONObject();
        response.setContentType("application/json;charset=utf-8");
        String rep_jsonStr = JSONUtil.getJSON(request);
        JSONObject rep_jsonObj = JSON.parseObject(rep_jsonStr);
        if(rep_jsonStr==null){
            message_jsonObj.put("message","未收到请求信息");
            response.getWriter().println(message_jsonObj);
            return;
        }
        try {
            Pagination pagination = ControllerHelper.getPagination(rep_jsonObj);
            Collection<School> schools = SchoolDaoImpl.getInstance().findAll();
            String schools_json = JSON.toJSONString(schools,JSONWriter.Feature.ReferenceDetection);
            message_jsonObj.put("totalNum", pagination.getTotalNum());
            message_jsonObj.put("data", schools_json);
            response.getWriter().println(message_jsonObj);
        } catch (BaseException e) {
            message_jsonObj.put("message", e.getMessage());
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        } catch (SQLException e) {
            message_jsonObj.put("message", "数据库操作异常");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        } catch (Exception e) {
            message_jsonObj.put("message", "网络异常");
            response.getWriter().println(message_jsonObj);
        }
    }
}
